<?php
declare (strict_types=1);

namespace app\controller;

use app\model\Goal as GoalModel;
use think\facade\Request;
use think\facade\Validate;

class Goal
{
    // 更新目标
    public function update()
    {
        $data = Request::post();

        $validate = Validate::rule([
            'goal_id' => 'require|integer',
            'title' => 'require|max:255',
            'description' => 'max:500',
            'due_date' => 'date',
        ]);

        if (!$validate->check($data)) {
            return json(['status' => 'error', 'message' => $validate->getError()]);
        }

        $goal = GoalModel::find($data['goal_id']);
        if (!$goal) {
            return json(['status' => 'error', 'message' => 'Goal not found']);
        }

        $goal->title = $data['title'];
        $goal->description = $data['description'] ?? $goal->description;
        $goal->due_date = $data['due_date'] ?? $goal->due_date;
        $goal->save();

        return json(['status' => 'success', 'message' => 'Goal updated successfully']);
    }

    // 删除目标
    public function delete()
    {
        $data = Request::post();

        $validate = Validate::rule([
            'goal_id' => 'require|integer',
        ]);

        if (!$validate->check($data)) {
            return json(['status' => 'error', 'message' => $validate->getError()]);
        }

        $goal = GoalModel::find($data['goal_id']);
        if (!$goal) {
            return json(['status' => 'error', 'message' => 'Goal not found']);
        }

        $goal->delete();

        return json(['status' => 'success', 'message' => 'Goal deleted successfully']);
    }
}
